<script setup name="OrderCurd">
import {
  orderAdd,
  orderDel,
  orderEdit,orderGetTypeList,orderGetLineList,orderDelLine
} from "@/api/wms/order";
import {getCurrentInstance, reactive} from "vue";
import {warehouseGetList} from "@/api/wms/warehouse";
import ProductSearch from "@/views/wms/product/search"

const {proxy} = getCurrentInstance();
const {sys_is, hrp_user_sex} = proxy.useDict('sys_is', 'hrp_user_sex');
let pd = reactive({
  orderType: {
    stockType: null, fmsType: null, loginName: null, costMoney: null, money: null,
    otherWhName: null, selfWhName: null, isCustomer: null, isSupplier: null, isStock: null
  },
  warehouseList: [],
  lineList: [],
  open: false,
  title: "",
  operation: 0,
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    typeId: null
  },
  rules: {
    enableFlag: [{
      required: true,
      message: "是否不能为空",
      trigger: "change"
    }],
    name: [{
      required: true,
      message: "名称不能为空",
      trigger: "blur"
    }],
    sex: [{
      required: true,
      message: "性别不能为空",
      trigger: "blur"
    }]
  }
});

function initOrderPage() {
  orderGetTypeList(pd.queryParams).then(res => {
    // 直接获取第一个省的在多写一个后端
    pd.orderType = res.data[0];
  });
  warehouseGetList({parentId: 0}).then(res => {
    pd.warehouseList = res.data;
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["orderRef"].validate(valid => {
    if (valid) {
      pd.form.line = pd.lineList;
      if (pd.operation == 1) {
        orderAdd(pd.form).then(res => {
          proxy.$modal.msgSuccess("新增成功");
          pd.open = false;
          emit("ok", pd.operation);
        });
      } else if (pd.operation == 2) {
        orderEdit(pd.form).then(res => {
          proxy.$modal.msgSuccess("修改成功");
          pd.open = false;
          emit("ok", pd.operation);
        });
      }
    }
  });
}
// 新增
function add(order) {
  reset();
  //合并
  pd.form = {...pd.form, ...order};
  pd.title = "新增单订";
  pd.operation = 1;
  pd.open = true;
  pd.lineList = [];
  pd.queryParams.typeId = order.typeId;
  pd.queryParams.isStock = order.isStock
  initOrderPage();
}

// update
function edit(order) {
  reset();
  //合并
  pd.form = {...pd.form, ...order};
  pd.title = "修改单订";
  pd.operation = 2;
  pd.open = true;
  pd.queryParams.typeId = order.typeId;
  pd.queryParams.isStock = order.isStock
  initOrderPage();
  getListLine();
}

// del
function del(id) {
  proxy.$modal.confirm('是否确认删除单订编号为:"' + id + '"的数据及子数据？').then(function () {
    return orderDel(id);
  }).then(() => {
    proxy.$modal.msgSuccess("删除成功");
    pd.open = false;
    pd.operation = 3;
    emit("ok", pd.operation);
  }).catch(() => {
  });
}

// 表单重置
function reset() {
  pd.form = {
    id: null,
    name: null,
    selfWhId: null,
    otherWhId: null,
    sourceId: null,
    deptId: null,
    typeId: null,
    typeName: null,
    manufacturerId: null,
    userApplicantId: null,
    userExecId: null,
    totalMoney: null,
    discountMoney: null,
    costMoney: null,
    state: "5",
    remark: null
  };
  pd.form.typeId = pd.queryParams.typeId;
  pd.form.isStock = pd.queryParams.isStock;
  pd.operation = 0;
  pd.title = "";
  proxy.resetForm("orderRef");
}

defineExpose({add, edit, del});
const emit = defineEmits(["ok"]);
//===============子表数据增删改查=========================================================
function computMoney(row) {
  row.costMoney = row.quantity * row.price - row.discountMoney
  row.totalMoney = row.costMoney
}
function getListLine(){
  if (!pd.form.id){
    return;
  }
  orderGetLineList({id: pd.form.id}).then(res => {
    pd.lineList = res.data;
  })
}
/** 新增按钮操作 */
function lineAdd(list) {
  list.forEach(item => {
    let line = {};
    line.productId = item.id;
    line.productName = item.name;
    line.measureUnit = item.measureUnit;
    line.price = item.price;
    line.attrValue = item.attrValue;
    line.batchCode = "0";
    line.price = item.price;
    line.quantity = 1;
    line.expireDate = null;
    line.totalMoney = item.price;
    line.costMoney = item.price;
    line.discountMoney = 0;
    line.money = 0;
    pd.lineList.push(line);
  });
}

/** 删除操作 */
function delLine(row) {
  let lineId = row.lineId
  if (lineId){
    proxy.$modal.confirm('是否确认删除 子单订编号为:"' + lineId + '"的数据项？').then(function () {
      return orderDelLine(lineId);
    }).then(() => {
      pd.lineList.splice(row,1);
      proxy.$modal.msgSuccess("删除成功");
    }).catch(() => {
    });
  } else {
    pd.lineList.splice(row,1);
  }
}
</script>

<template>
  <!-- 添加或修改单订对话框 -->
  <el-dialog :title="pd.title" v-model="pd.open" width="1000px" append-to-body>
    <el-form ref="orderRef" :model="pd.form" :rules="pd.rules" label-width="80px">
      <el-row>
        <el-col :span="6">
            <el-form-item label="订单名称" prop="name" width="80px">
              <el-input v-model="pd.form.name" placeholder="请输入订单名称"/>
            </el-form-item>
          <el-form-item label="状态" prop="state">
            <el-input disabled v-model="pd.form.state" placeholder="请输入订单名称"/>
          </el-form-item>
          <el-form-item label="总金额" prop="totalMoney">
            <el-input disabled v-model="pd.form.totalMoney" placeholder="总金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="pd.orderType.loginName != 'hide'" :label="pd.orderType.loginName" prop="userId">
              <el-input v-model="pd.form.userId" placeholder="请输入用户id"/>
          </el-form-item>
          <el-form-item v-if="pd.orderType.selfWhName !== 'hide'" :label="pd.orderType.selfWhName" prop="selfWhId">
            <el-select v-model="pd.form.selfWhId" placeholder="己方仓库" clearable>
              <el-option v-for="item in pd.warehouseList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="申请人" prop="userId">
            <el-input v-model="pd.form.userApplicantId" placeholder="请输入订单名称"/>
          </el-form-item>
          <el-form-item label="优惠金额" prop="discountMoney">
            <el-input disabled v-model="pd.form.discountMoney" placeholder="优惠金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item v-if="pd.operation != 2 && pd.orderType.otherWhName != 'hide'" :label="pd.orderType.otherWhName"
                        prop="otherWhId">
            <el-input v-model="pd.form.otherWhId" placeholder="己方仓库"/>
          </el-form-item>
          <el-form-item label="订单来源" prop="state">
            <el-input disabled v-model="pd.form.sourceId" placeholder="订单来源"/>
          </el-form-item>
          <el-form-item label="执行人" prop="userId">
            <el-input v-model="pd.form.userExecId" placeholder="请输入订单名称"/>
          </el-form-item>
          <el-form-item :label="pd.orderType.costMoney" prop="discountMoney">
            <el-input disabled v-model="pd.form.costMoney" placeholder="优惠金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="开单部门" prop="userId">
            <el-input v-model="pd.form.deptId" placeholder="部门"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="pd.form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="pd.operation===1" icon="Plus" type="success" @click="submitForm">保存</el-button>
        <el-button v-if="pd.operation===2" icon="Delete" type="danger" @click="del(pd.form.id)">删除</el-button>
      </el-col>
      <el-col v-if="pd.operation===2" :span="1.5">
        <el-button icon="Plus" type="success" @click="submitForm">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="Close" type="info" @click="pd.open = false">关闭</el-button>
      </el-col>
      <el-col :span="1.5">
        <ProductSearch :searchType=2 :isSingle="false" :params="{isStock: pd.queryParams.isStock}" @ok="lineAdd" />
      </el-col>
      <el-col :span="1.5">
        <el-button icon="Refresh" @click="getListLine">刷新</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="pd.loading" :data="pd.lineList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="产品id" align="center" prop="productId" width="130"/>
      <el-table-column label="产品名称" align="center" prop="productName"/>
      <el-table-column label="单位" align="center" prop="measureUnit" width="50"/>
      <el-table-column label="批次号" prop="batchCode" align="center">
        <template #default="scope">
          <el-input v-model="scope.row.batchCode"  placeholder="请输入批次号，默认是0" />
        </template>
      </el-table-column>
      <el-table-column label="单价" align="center" prop="price" width="80"/>
      <el-table-column label="数量" prop="quantity" width="80">
        <template #default="scope">
          <el-input @input="computMoney(scope.row)" v-model="scope.row.quantity"  placeholder="请输入优惠金额" />
        </template>
      </el-table-column>
      <el-table-column label="优惠金额" prop="quantity" width="80">
        <template #default="scope">
          <el-input @input="computMoney(scope.row)" v-model="scope.row.discountMoney"  placeholder="请输入优惠金额" />
        </template>
      </el-table-column>
      <el-table-column :label="pd.orderType.costMoney" prop="costMoney" width="100"/>
      <el-table-column label="总金额" align="center" prop="totalMoney" width="100"/>
      <el-table-column :label="pd.orderType.money" prop="money" width="100"/>
      <el-table-column label="产品有效期" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库位ID" prop="areaId" align="center"/>
      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" width="80">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="delLine(scope.row,scope.$index)"
                     v-hasPermi="['wms:order:del']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>

  <!-- 添加或修改子数据项
  <el-dialog :title="pdLine.title" v-model="pdLine.open" width="700px" append-to-body>
    <el-form ref="orderLineRef" :model="pdLine.form" :rules="pdLine.rules" label-width="80px">
      <el-row>
        <el-col :span="6">
          <el-form-item label="名称" prop="name" width="80px">
            <el-input v-model="pdLine.form.name" placeholder="请输入名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="启用" prop="enableFlag">
            <el-switch v-model="pdLine.form.enableFlag" active-value="0" inactive-value="1"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="state">
            <el-switch v-model="pdLine.form.state" active-value="0" inactive-value="1"></el-switch>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="pdLine.form.remark" type="textarea" placeholder="请输入内容"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="pdLine.operation===1" type="primary" @click="submitLineForm">新 增</el-button>
        <el-button v-if="pdLine.operation===2" type="success" @click="submitLineForm">修 改</el-button>
        <el-button v-if="pdLine.operation===2" type="danger" @click="delLine(pd.form.id)">删 除</el-button>
        <el-button type="info" @click="pdLine.open = false">关 闭</el-button>
      </div>
    </template>
  </el-dialog>-->
</template>

<style lang='scss' scoped>

</style>